//% color="#C32D20" iconWidth=30 iconHeight=20
namespace oled12864 {
    //% block="开关" blockType="tag"
    export function keySwitch() { }
    //% block="read tilt switch digital pin [PIN1] [STATE]" blockType="boolean"
    //% PIN1.shadow="dropdown"  PIN1.options="PIN_DigitalRead"
    //% STATE.shadow="dropdown"  STATE.options="STATE_TILT_SWITCH"
    export function tiltSwitchRead(parameter: any, block: any) {
        let pin = parameter.PIN1.code;
        let state = parameter.STATE.code;
        Generator.addCode([`digitalRead(${pin}) == ${state}`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="read digital pin [PIN1] [STATE]" blockType="boolean"
    //% PIN1.shadow="dropdown"  PIN1.options="PIN_DigitalRead"
    //% STATE.shadow="dropdown"  STATE.options="STATE"
    export function digitalRead(parameter: any, block: any) {
        let pin = parameter.PIN1.code;
        let state = parameter.STATE.code;
        Generator.addCode([`digitalRead(${pin}) == ${state}`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="巡线" blockType="tag"
    export function patrol() { }
    //% block="read the [PIN10] [PATROL]" blockType="boolean"
    //% PIN10.shadow="dropdown"  PIN10.options="PIN_DigitalRead2"
    //% PATROL.shadow="dropdown" PATROL.options="PIN_DigitalRead1"    
    export function readPatrol(parameter: any, block: any) {
        let pin = parameter.PIN10.code;
        let patrol = parameter.PATROL.code;
        let targetPin = ''

        if (pin === '2' && patrol === 'A') {
            targetPin = '21'
        } else if (pin === '2' && patrol === 'B') {
            targetPin = '22'
        } else if (pin === '3' && patrol === 'A') {
            targetPin = 'D13'
        } else if (pin === '3' && patrol === 'B') {
            targetPin = 'D7'
        } else if (pin === '4' && patrol === 'A') {
            targetPin = 'D12'
        } else if (pin === '4' && patrol === 'B') {
            targetPin = 'D11'
        }

        Generator.addCode([`digitalRead(${targetPin})`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="12c tracing [PIN] hit the black line" blockType="boolean"
    //% PIN.shadow="dropdown"  PIN.options="PIN_DigitalRead2"
    export function hitBlackLine(parameter: any) {
        let pin = parameter.PIN.code;
        if (pin === '3') {
            Generator.addCode([`(digitalRead(D13)==1) || (digitalRead(D7)==1)`, Generator.ORDER_UNARY_POSTFIX]);
        } else if (pin === '2') {
            Generator.addCode([`(digitalRead(21)==1) || (digitalRead(22)==1)`, Generator.ORDER_UNARY_POSTFIX]);
        } else {
            Generator.addCode([`(digitalRead(D12)==1) || (digitalRead(D11)==1)`, Generator.ORDER_UNARY_POSTFIX]);
        }
    }

    //% block="红外" blockType="tag"
    export function infrared() { }
    //% block="the infrared remote [KEY] is" blockType="reporter"
    //% PIN.shadow="dropdown" PIN.options="PIN_DigitalWrite"
    //% KEY.shadow="dropdown" KEY.options="KEY_OPTIONS"
    export function readKey(parameter: any) {
        // let pin = parameter.PIN.code;
        let key = parameter.KEY.code;
        // Generator.addInclude('DFRobot_IRremote', '#include <DFRobot_IRremote.h>');
        // Generator.addObject(`remoteReceive_${pin}`, `IRremote_Receive`, `remoteReceive_${pin};`);
        // Generator.addSetup(`remoteReceive_${pin}.begin`, `remoteReceive_${pin}.begin(${pin});`);
        // Generator.addCode([`remoteReceive_${pin}.getIrCommand()==String("${key}")`, Generator.ORDER_UNARY_POSTFIX]);
        Generator.addCode(`String("${key}")`);
    }

    //% block="read the [PIN9] infrared received value" blockType="reporter"
    //% PIN9.shadow="dropdown" PIN9.options="PIN_DigitalWrite"
    export function readInfrared(parameter: any, block: any) {
        let pin = parameter.PIN9.code;
        Generator.addInclude('DFRobot_IRremote', '#include <DFRobot_IRremote.h>');
        Generator.addObject(`remoteReceive_${pin}`, `IRremote_Receive`, `remoteReceive_${pin};`);
        Generator.addSetup(`remoteReceive_${pin}.begin`, `remoteReceive_${pin}.begin(${pin});`);
        Generator.addCode(`remoteReceive_${pin}.getIrCommand()`);
    }

    //% block="雨滴" blockType="tag"
    export function raindrop() { }
    //% block="read raindrop module pin [PIN2]" blockType="reporter"
    //% PIN2.shadow="dropdown"  PIN2.options="PIN_AnalogRead"
    export function readRaindropModule(parameter: any, block: any) {
        let pin = parameter.PIN2.code;
        // pin = Math.floor(pin / 16) || 0;
        Generator.addCode([`analogRead(${pin})`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="旋钮" blockType="tag"
    export function knob() { }
    //% block="read analog pin [PIN2]" blockType="reporter"
    //% PIN2.shadow="dropdown"  PIN2.options="PIN_AnalogRead"
    export function analogRead(parameter: any, block: any) {
        let pin = parameter.PIN2.code;
        // pin = Math.floor(pin / 16) || 0;
        Generator.addCode([`analogRead(${pin})`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="光敏" blockType="tag"
    export function light() { }
    //% block="read analog pin [PIN2]" blockType="reporter"
    //% PIN2.shadow="dropdown"  PIN2.options="PIN_AnalogRead"
    export function analogRead1(parameter: any, block: any) {
        let pin = parameter.PIN2.code;
        Generator.addCode([`analogRead(${pin})`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="灯光" blockType="tag"
    export function led() { }
    //% block="digital pin [PIN4] output [LED_STATE]" blockType="command"
    //% PIN4.shadow="dropdown"  PIN4.options="PIN_DigitalWrite"
    //% LED_STATE.shadow="dropdown"  LED_STATE.options="LED_STATE"
    export function digitalWrite(parameter: any, block: any) {
        let pin = parameter.PIN4.code;
        let val = parameter.LED_STATE.code;
        Generator.addCode(`digitalWrite(${pin},${val});`);
    }

    //% block="init the RGB light [PIN5]" blockType="command"
    //% PIN5.shadow="dropdown" PIN5.options="PIN_DigitalWrite"
    export function initLed(parameter: any, block: any) {
        let pin = parameter.PIN5.code;
        Generator.addInclude('DFRobot_NeoPixel', '#include <DFRobot_NeoPixel.h>');
        Generator.addObject(`neoPixel_${pin}`, `DFRobot_NeoPixel`, `neoPixel_${pin};`);
        Generator.addSetup(`neoPixel_${pin}.begin`, `neoPixel_${pin}.begin(${pin}, 1);`);
    }

    //% block="RGB light Set the brightness of the [PIN6] light to [SR]" blockType="command"
    //% PIN6.shadow="dropdown" PIN6.options="PIN_DigitalWrite"
    //% SR.shadow="range"   SR.params.min=0    SR.params.max=255    SR.defl=255
    export function setLight(parameter: any, block: any) {
        let pin = parameter.PIN6.code;
        let light = parameter.SR.code;
        Generator.addCode(`neoPixel_${pin}.setBrightness(${light});`);
    }

    //% block="RGB light [PIN7] display [COLOR]" blockType="command"
    //% PIN7.shadow="dropdown" PIN7.options="PIN_DigitalWrite"
    //% COLOR.shadow="colorPalette"
    export function setColor(parameter: any, block: any) {
        let pin = parameter.PIN7.code;
        let color = parameter.COLOR.code;
        Generator.addCode(`neoPixel_${pin}.setRangeColor(${0}, ${0}, ${color});`);
    }

    //% block="All RGB lamp [PIN8] are off" blockType="command"
    //% PIN8.shadow="dropdown" PIN8.options="PIN_DigitalWrite"
    export function clearAll(parameter: any, block: any) {
        let pin = parameter.PIN8.code;
        Generator.addCode(`neoPixel_${pin}.clear();`);
    }

    //% block="蜂鸣器" blockType="tag"
    export function buzzer() { }
    //% block="pwm pin[PIN3] output [PWM]" blockType="command"
    //% PIN3.shadow="dropdown"  PIN3.options="PIN_AnalogWrite"
    //% PWM.shadow="range" PWM.params.min=0  PWM.params.max=1023  PWM.defl=666
    export function analogWrite(parameter: any, block: any) {
        let pin = parameter.PIN3.code;
        let pwm = parameter.PWM.code;
        Generator.addCode(`analogWrite(${pin},${pwm});`);
    }

    //% block="超声波" blockType="tag"
    export function ultrasonic() { }
    //% block="Read ultrasonic sensor distance [UNIT] pin [PIN]" blockType="reporter"
    //% UNIT.shadow="dropdown" UNIT.options="UNIT"
    //% PIN.shadow="dropdown" PIN.options="PIN_DigitalRead3"
    export function readDistance(parameter: any, block: any) {
        let unit = parameter.UNIT.code;
        let pin = parameter.PIN.code;
        let trig = ''
        let echo = ''

        if (pin === '3') {
            trig = 'D7'
            echo = 'D13'
        } else if (pin === '4') {
            trig = 'D11'
            echo = 'D12'
        }
        Generator.addInclude('DFRobot_URM10', '#include <DFRobot_URM10.h>');
        Generator.addObject(`urm10`, `DFRobot_URM10`, `urm10;`);
        Generator.addCode(`urm10.getDistance${unit}(${trig}, ${echo})`);
    }

    //% block="颜色识别" blockType="tag"
    export function color() { }
    //% block="Initialize the TCS34725 color sensor"
    export function initTCS(parameter: any, block: any) {
        Generator.addInclude('DFRobot_TCS34725', '#include <DFRobot_TCS34725.h>');
        Generator.addObject(`tcs34725`, `DFRobot_TCS34725`, `tcs34725;`);
        Generator.addSetup(`tcs34725.begin`, `tcs34725.begin();`);
        Generator.addSetup(`digitalWrite_D3_HIGH`, `digitalWrite(D3, HIGH);`);
    }

    //% block="Read the TCS34725 color sensor[COLOR][ISGAMMA]" blockType="reporter"
    //% COLOR.shadow="dropdown" COLOR.options="COLOR"
    //% ISGAMMA.shadow="dropdown" ISGAMMA.options="ISGAMMA"
    export function readTCS(parameter: any, block: any) {
        let color = parameter.COLOR.code;
        let isGamma = parameter.ISGAMMA.code;
        let func = isGamma === 'ToGamma' ? `tcs34725.get${color}ToGamma` : `tcs34725.get${color}`
        Generator.addCode(`${func}()`);
    }

    //% block="电机" blockType="tag"
    export function motor() { }
    //% block="Motor initialization"
    export function initMotor() {
        Generator.addSetup(`Serial.begin`, `Serial.begin(9600);`);
    }

    //% block="read [PIN][BEARING] speed is [SR]" blockType="command"
    //% PIN.shadow="dropdown" PIN.options="PIN_MOptions"
    //% BEARING.shadow="dropdown" BEARING.options="BEARING_OPTIONS"
    //% SR.shadow="range"   SR.params.min=0    SR.params.max=100    SR.defl=100
    export function setSpeedAndBearing(parameter: any, block: any) {
        let pin = parameter.PIN.code;
        let bearing = parameter.BEARING.code;
        let speed = parameter.SR.code;
        // Generator.addCode(`Serial.println("${pin}_SR(${bearing}, ${speed})");`);
        Generator.addCode(`Serial.println((String("${pin}_SR(${bearing},") + String((String((String(${speed}).toInt())) + String(")")))));`);
        Generator.addCode("delay(100);");
    }

    //% block="四位数码管" blockType="tag"
    export function fourDigit() { }
    //% block="set led num [NUM]" blockType="command"
    //% NUM.shadow="number"  NUM.defl="1234"
    export function setNum(parameter: any) {
        let num = parameter.NUM.code;

        Generator.addSetup(`Serial.begin`, `Serial.begin(9600);`);
        // Generator.addCode(`Serial.println("SMG(${num})");`);
        Generator.addCode(`Serial.println((String("SMG(") + String((String((String(${num}).toInt())) + String(")")))));`);
        Generator.addCode("delay(100);");
    }

    //% block="[LEFT] [RIGHT]" blockType="command"
    //% LEFT.shadow="normal"  LEFT.defl="12"
    //% RIGHT.shadow="normal"  RIGHT.defl="34"
    export function compLeftAndRight(parameter: any) {
        let left = parameter.LEFT.code;
        let right = parameter.RIGHT.code;

        // Generator.addCode(`if (((${left}<0) || (${left}>99))) {\n`+
        //     `    ${left} = 0;\n`+
        //     `  }`
        // )

        // Generator.addCode(`if (((${right}<0) || (${right}>99))) {\n`+
        //     `    ${right} = 0;\n`+
        //     `  }`
        // )

        Generator.addSetup(`Serial.begin`, `Serial.begin(9600);`);
        Generator.addCode(`Serial.println(String("SMG(") + String(String(String(${left}).toInt()) + String(".") + String(String(${right}).toInt()) + String(")")));`);
        Generator.addCode("delay(100);");
        // Generator.addCode(`Serial.println("SMG(${left}.${right})");`);
    }

    //% block="Four-digit numeral tube [STATE]" blockType="command"
    //% STATE.shadow="dropdown" STATE.options="STATE_OPTIONS"
    export function setTubeState(parameter: any) {
        let state = parameter.STATE.code;
        Generator.addSetup(`Serial.begin`, `Serial.begin(9600);`);
        Generator.addCode(`Serial.println("SMG(${state})");`);
        Generator.addCode("delay(100);");
    }

    //% block="温湿度" blockType="tag"
    export function temperatureAndHumidity() { }

    //% block="Read temperature and humidity [PIN] [TYPE]"  blockType="reporter"
    //% PIN.shadow="dropdown" PIN.options="PIN_DigitalWrite"
    //% TYPE.shadow="dropdown" TYPE.options="TEMPERATURE_HUMIDITY_TYPE"
    export function readTemperatureAndHumidity(parameter: any) {
        let pin = parameter.PIN.code;
        let type = parameter.TYPE.code;

        Generator.addInclude(`DFRobot_DHT.h`, `#include <DFRobot_DHT.h>`)
        Generator.addObject(`dht11_${pin}`, `DFRobot_DHT`, `dht11_${pin};`);
        Generator.addSetup(`dht11_${pin}.begin`, `dht11_${pin}.begin(${pin}, DHT11);`);
        Generator.addCode([`dht11_${pin}.${type}()`, Generator.ORDER_UNARY_POSTFIX]);
    }

    //% block="OLED" blockType="tag"
    export function oled() { }

    //% block="OLED 128*64 initialize I2C address [ADDR]" blockType="command"
    //% ADDR.shadow="number"   ADDR.defl="0x3c"
    export function initOled(param: any) {
        const addr = param.ADDR.code;

        Generator.addInclude('U8g2lib.h', '#include <U8g2lib.h>');
        Generator.addInclude('MPython.h', '#include <MPython.h>');
        Generator.addInclude('DFRobot_Task.h', '#include <DFRobot_Task.h>');
        Generator.addInclude('DFRobot_NeoPixel.h', '#include <DFRobot_NeoPixel.h>');

        Generator.addInclude(`mind_n_ch`, `// 动态变量\n` +
            `volatile float mind_n_ch;\n` +
            `volatile float mind_n_en;\n`
        )

        Generator.addInclude(`u8g2_12864`, `// 创建对象\n` +
            `U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2_12864(U8G2_R0, U8X8_PIN_NONE);\n` +
            `DFRobot_NeoPixel neoPixel_33;\n`
        )

        // Generator.addObject(`u8g2_12864`, `U8G2_SSD1306_128X64_NONAME_F_HW_I2C`, `u8g2_12864(U8G2_R0, U8X8_PIN_NONE);`)
        // Generator.addObject(`neoPixel_33`, `DFRobot_NeoPixel`, `neoPixel_33;`)

        Generator.addInclude(`oled12864Begin`, `// 函数声明\n` +
            `void oled12864Begin(uint8_t addr, uint8_t dir);\n` +
            `void oled12864Print(String text, uint8_t x, uint8_t y);\n\n` +
            `void oled12864Begin(uint8_t addr, uint8_t dir) {\n` +
            `  u8g2_12864.setI2CAddress(addr<<1);\n` +
            `  u8g2_12864.begin();\n` +
            `  u8g2_12864.enableUTF8Print();\n` +
            `  u8g2_12864.setFont(u8g2_font_wqy16_t_gb2312);\n` +
            `  u8g2_12864.setFontDirection(dir);\n` +
            `  u8g2_12864.firstPage();\n` +
            `}\n` +
            `void oled12864Print(String text, uint8_t x, uint8_t y) {\n` +
            `  u8g2_12864.setCursor(x, y);\n` +
            `  u8g2_12864.print(text);\n` +
            `  u8g2_12864.nextPage();\n` +
            `}\n`
        )

        Generator.addSetup(`oled12864`, `taskStart();\n` +
            `  mPython.begin();\n` +
            `  oled12864Begin(${addr}, 0);\n` +
            `  neoPixel_33.begin(33, 1);\n` +
            `  neoPixel_33.setBrightness(20);\n` +
            `  neoPixel_33.setRangeColor(0, 0, 0xFFFFFF);\n` +
            `  mind_n_ch = 0; // 左右按键\n` +
            `  mind_n_en = 1; // 确认按键\n` +
            `  taskFree();\n`
        )
    }

    //% block="OLED 128*64 display text [TEXT] in coordinates X:[XV] Y:[YV]" blockType="command"
    //% TEXT.shadow="string"   TEXT.defl="Mind+育伟达"
    //% XV.shadow="range"   XV.params.min=0    XV.params.max=127    XV.defl=8
    //% YV.shadow="range"   YV.params.min=0    YV.params.max=47    YV.defl=16
    export function displayText(param: any) {
        const text = param.TEXT.code;
        const xv = param.XV.code;
        const yv = param.YV.code;
        Generator.addCode(`oled12864Print(${text}, ${xv}, ${yv + 16});`)
    }

    //% block="OLED 128*64 clear screen" blockType="command"
    export function clearScreen() {
        Generator.addCode(`u8g2_12864.clear();`)
    }

    //% block="Key function module" blockType="command"
    export function keyModule() {
        Generator.addCode(`if ((digitalRead(19) == 0) && (mind_n_ch > 0)) {\n` +
            `    delay(10);\n` +
            `    if ((digitalRead(19) == 0) && (mind_n_ch > 0)) {\n` +
            `        mind_n_ch -= 1;\n` +
            `    }\n` +
            `    while (digitalRead(19) == 0) {\n` +
            `        delay(10);\n` +
            `        buzz.redirect(23);\n` +
            `        buzz.freq(147, BEAT_1_4);\n` +
            `    }\n` +
            `    u8g2_12864.clear();\n` +
            `  }\n` +
            `  if ((digitalRead(18) == 0) && (mind_n_ch < 7)) {\n` +
            `    delay(10);\n` +
            `    if ((digitalRead(18) == 0) && (mind_n_ch < 7)) {\n` +
            `        mind_n_ch += 1;\n` +
            `    }\n` +
            `    while (digitalRead(18) == 0) {\n` +
            `        delay(10);\n` +
            `        buzz.redirect(23);\n` +
            `        buzz.freq(147, BEAT_1_4);\n` +
            `    }\n` +
            `    u8g2_12864.clear();\n` +
            `  }\n` +
            `  if ((digitalRead(5) == 0)) {\n` +
            `    delay(10);\n` +
            `    if ((digitalRead(5) == 0)) {\n` +
            `        mind_n_en = !mind_n_en;\n` +
            `    }\n` +
            `    while (digitalRead(5) == 0) {\n` +
            `        delay(10);\n` +
            `        buzz.redirect(23);\n` +
            `        buzz.freq(147, BEAT_1_4);\n` +
            `    }\n` +
            `  }\n` +
            `  while (mind_n_en == 0) {\n` +
            `   delay(10);\n` +
            `   if ((mind_n_en==0)) {\n` +
            `     if ((mind_n_ch==0)) {\n` +
            `       taskStart(loop1);\n` +
            `     }\n` +
            `     if ((mind_n_ch==1)) {\n` +
            `       taskStart(loop2);\n` +
            `     }\n` +
            `     if ((mind_n_ch==2)) {\n` +
            `       taskStart(loop3);\n` +
            `     }\n` +
            `     if ((mind_n_ch==3)) {\n` +
            `       taskStart(loop4);\n` +
            `     }\n` +
            `     if ((mind_n_ch==4)) {\n` +
            `       taskStart(loop5);\n` +
            `     }\n` +
            `     if ((mind_n_ch==5)) {\n` +
            `       taskStart(loop6);\n` +
            `     }\n` +
            `     if ((mind_n_ch==6)) {\n` +
            `       taskStart(loop7);\n` +
            `     }\n` +
            `     if ((mind_n_ch==7)) {\n` +
            `       taskStart(loop8);\n` +
            `     }\n` +
            `   }\n` +
            `   if ((digitalRead(5) == 0)) {\n` +
            `       delay(10);\n` +
            `       if ((digitalRead(5) == 0)){\n` +
            `         mind_n_en = !mind_n_en;\n` +
            `       }\n` +
            `       while (digitalRead(5) == 0) {\n` +
            `         delay(10);\n` +
            `         buzz.redirect(23);\n` +
            `	        buzz.freq(147, BEAT_1_4);\n` +
            `       }\n` +
            `   }\n` +
            ` }\n` +
            ` if ((mind_n_ch==0)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务一", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==1)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务二", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==2)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务三", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==3)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务四", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==4)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务五", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==5)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务六", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==6)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务七", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_ch==7)) {\n` +
            `   oled12864Print("育伟达主控", 24, 32);\n` +
            `   oled12864Print("任务八", 40, 56);\n` +
            ` }\n` +
            ` if ((mind_n_en==1)) {\n` +
            `   if ((mind_n_ch==0)) {\n` +
            `     taskFree(loop1);\n` +
            `   }\n` +
            `   if ((mind_n_ch==1)) {\n` +
            `     taskFree(loop2);\n` +
            `   }\n` +
            `   if ((mind_n_ch==2)) {\n` +
            `     taskFree(loop3);\n` +
            `   }\n` +
            `   if ((mind_n_ch==3)) {\n` +
            `     taskFree(loop4);\n` +
            `   }\n` +
            `   if ((mind_n_ch==4)) {\n` +
            `     taskFree(loop5);\n` +
            `   }\n` +
            `   if ((mind_n_ch==5)) {\n` +
            `     taskFree(loop6);\n` +
            `   }\n` +
            `   if ((mind_n_ch==6)) {\n` +
            `     taskFree(loop7);\n` +
            `   }\n` +
            `   if ((mind_n_ch==7)) {\n` +
            `     taskFree(loop8);\n` +
            `   }\n` +
            ` }\n`
        )
    }
}
